package com.ssy.lingxi.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.ssy.lingxi.common.constant.CommonConstant;
import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.response.PageData;
import com.ssy.lingxi.common.response.PageModel;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.platform.manage.api.feign.paas.SitePAASControllerFeign;
import com.ssy.lingxi.platform.manage.api.model.dto.site.SitePAASDTO;
import com.ssy.lingxi.system.dao.FriendUrlRepository;
import com.ssy.lingxi.system.dao.SiteRepository;
import com.ssy.lingxi.system.dao.SiteShopRepository;
import com.ssy.lingxi.system.dto.request.SiteAddRequest;
import com.ssy.lingxi.system.dto.request.SiteDetailsResquest;
import com.ssy.lingxi.system.dto.request.SiteUpdateResquest;
import com.ssy.lingxi.system.dto.request.SiteUpdateStateResquest;
import com.ssy.lingxi.system.dto.response.SiteAllResponse;
import com.ssy.lingxi.system.dto.response.SiteDetailsResponse;
import com.ssy.lingxi.system.dto.response.SiteListResponse;
import com.ssy.lingxi.system.entity.FriendUrl;
import com.ssy.lingxi.system.entity.Site;
import com.ssy.lingxi.system.entity.SiteShop;
import com.ssy.lingxi.system.model.constant.RoleConstant;
import com.ssy.lingxi.system.service.SiteService;
import com.ssy.lingxi.system.utils.UserDetailsUtil;
import org.springframework.data.domain.Sort;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class SiteServiceImpl implements SiteService {
    @Resource
    SiteRepository siteRepository;
    @Resource
    UserDetailsUtil userDetailsUtil;
    @Resource
    FriendUrlRepository friendUrlRepository;
    @Resource
    JdbcTemplate jdbcTemplate;
    @Resource
    SiteShopRepository siteShopRepository;
    @Resource
    SitePAASControllerFeign siteControllerFeign;

    /**
     * 添加站点
     *
     * @param httpServletRequest
     * @param request
     * @author wrc
     * @date 2020/6/3
     */
    @Transactional
    @Override
    public Wrapper siteAdd(HttpServletRequest httpServletRequest, SiteAddRequest request) {
        Site site = siteRepository.queryByNameEquals(request.getName());
        if (null != site && null != site.getName()) {
            return Wrapper.fail("站点名字已存在");
        }
        Site siteNew = new Site();
        siteNew.setCountryId(request.getCountryId());
        siteNew.setCurrencyId(request.getCurrencyId());
        siteNew.setDescribe(request.getDescribe());
        siteNew.setDomainName(request.getDomainName());
        siteNew.setLanguageId(request.getLanguageId());
        siteNew.setUrl(request.getUrl());
        siteNew.setState(request.getState());
        siteNew.setPutOnRecords(request.getPutOnRecords());
        siteNew.setName(request.getName());
        siteNew.setLogo(request.getLogo());
        siteNew.setCreateTime(System.currentTimeMillis());
        siteNew.setCreateRoleId(userDetailsUtil.getLoginUserDetails(httpServletRequest).getId());
        siteNew.setEnableMultiTenancy(request.getEnableMultiTenancy());
        Site save = siteRepository.saveAndFlush(siteNew);
        List<FriendUrl> friendUrls = request.getFriendUrls();
        friendUrlRepository.saveAll(friendUrls);
        List<SiteShop> siteShops = new ArrayList<>();
        request.getShopIds().forEach(shopId -> {
            SiteShop siteShop = new SiteShop();
            siteShop.setShopId(shopId);
            siteShop.setSiteId(save.getId());
            siteShops.add(siteShop);
        });
        siteShopRepository.saveAll(siteShops);

        SitePAASDTO synSiteRequest = new SitePAASDTO();
        BeanUtil.copyProperties(siteNew, synSiteRequest);
        synSiteRequest.setShopIds(request.getShopIds());
        Wrapper wrapper = siteControllerFeign.add(synSiteRequest);

        return wrapper;
    }

    /**
     * 站点列表
     *
     * @param request
     * @author wrc
     * @date 2020/6/3
     */
    @Override
    public Wrapper<PageData<SiteListResponse>> siteList(PageModel request) {
        StringBuilder sbList = new StringBuilder();
        StringBuilder sbCount = new StringBuilder();
        sbList.append("SELECT cs.id as id,cs.name,cs.domain_name as domainName,ca.name as  country,cc.name as  currency,cl.name as language,cs.state as state FROM cf_site cs LEFT JOIN cf_currency cc ON cc.ID = cs.currency_id LEFT JOIN cf_language cl ON cl.ID = cs.language_id LEFT JOIN cf_country_area ca ON ca.ID = cs.country_id WHERE 1=1  ");
        sbCount.append("select  count(distinct  cs.id)  FROM cf_site cs LEFT JOIN cf_currency cc ON cc.ID = cs.currency_id LEFT JOIN cf_language cl ON cl.ID = cs.language_id LEFT JOIN cf_country_area ca ON ca.ID = cs.country_id WHERE 1=1  ");
        sbList.append(" order by  cs.id desc ");
        sbList.append(" limit ");
        sbList.append(request.getPageSize());
        sbList.append(" OFFSET ");
        sbList.append(request.getCurrent() * request.getPageSize());
        Long count = jdbcTemplate.queryForObject(sbCount.toString(), Long.class);
        List<SiteListResponse> query = jdbcTemplate.query(sbList.toString(), new BeanPropertyRowMapper(SiteListResponse.class));
        return Wrapper.success(new PageData<>(count, query));
    }

    /**
     * 站点详情查询
     *
     * @param request
     * @author wrc
     * @date 2020/6/3
     */
    @Override
    public Wrapper<SiteDetailsResponse> siteDetails(SiteDetailsResquest request) {
        SiteDetailsResponse response = new SiteDetailsResponse();
        Optional<Site> byId = siteRepository.findById(request.getId());
        if (!byId.isPresent()) {
            return Wrapper.fail(ResponseCode.SY_SITE_INFORMATION_DOES_NOT_EXIST);
        }
        Site site = byId.get();
        response.setCountryId(site.getCountryId());
        response.setCurrencyId(site.getCurrencyId());
        response.setDescribe(site.getDescribe());
        response.setDomainName(site.getDomainName());
        response.setLanguageId(site.getLanguageId());
        response.setUrl(site.getUrl());
        response.setState(site.getState());
        response.setPutOnRecords(site.getPutOnRecords());
        response.setName(site.getName());
        response.setLogo(site.getLogo());
        response.setEnableMultiTenancy(site.getEnableMultiTenancy());
        List<SiteShop> siteShops = siteShopRepository.findBySiteId(site.getId());
        List<Long> collect = siteShops.stream().map(siteShop -> siteShop.getShopId()).collect(Collectors.toList());
        response.setShopIds(collect);
        response.setFriendUrls(friendUrlRepository.findAllBySiteIdEquals(request.getId()));
        return Wrapper.success(response);
    }

    /**
     * 删除站点
     *
     * @param request
     * @author wrc
     * @date 2020/6/3
     */
    @Transactional
    @Override
    public Wrapper siteDelete(SiteDetailsResquest request) {
        Optional<Site> byId = siteRepository.findById(request.getId());
        if (!byId.isPresent()) {
            return Wrapper.fail("站点信息不存在");
        }
        if (RoleConstant.State.STATE_VALID == byId.get().getState()) {
            return Wrapper.fail("站点处于正常状态不可删除");
        }
        siteRepository.deleteById(request.getId());

        SitePAASDTO synSiteRequest = new SitePAASDTO();
        synSiteRequest.setId(request.getId());
        Wrapper wrapper = siteControllerFeign.delete(synSiteRequest);

        return Wrapper.success();
    }

    /**
     * 修改站点
     *
     * @param request
     * @author wrc
     * @date 2020/6/3
     */
    @Transactional
    @Override
    public Wrapper siteUpdate(SiteUpdateResquest request) {
        Optional<Site> byId = siteRepository.findById(request.getId());
        if (!byId.isPresent()) {
            return Wrapper.fail(ResponseCode.SY_SITE_INFORMATION_DOES_NOT_EXIST);
        }
        if (RoleConstant.State.STATE_VALID == byId.get().getState()) {
            return Wrapper.fail(ResponseCode.SY_SITE_NORMAL_STATE_CANNOT_BE_MODIFIED);
        }
        Site site = new Site();
        site.setId(request.getId());
        site.setCountryId(request.getCountryId());
        site.setCurrencyId(request.getCurrencyId());
        site.setDescribe(request.getDescribe());
        site.setDomainName(request.getDomainName());
        site.setLanguageId(request.getLanguageId());
        site.setUrl(request.getUrl());
        site.setState(request.getState());
        site.setPutOnRecords(request.getPutOnRecords());
        site.setName(request.getName());
        site.setLogo(request.getLogo());
        site.setUpdateTime(System.currentTimeMillis());
        site.setEnableMultiTenancy(request.getEnableMultiTenancy());
        siteRepository.save(site);
        siteShopRepository.deleteAllBySiteId(site.getId());
        List<SiteShop> siteShop = new ArrayList<>();
        request.getShopIds().forEach(id -> {
            SiteShop ss = new SiteShop();
            ss.setSiteId(site.getId());
            ss.setShopId(id);
            siteShop.add(ss);
        });
        siteShopRepository.saveAll(siteShop);
        friendUrlRepository.saveAll(request.getFriendUrls());

        SitePAASDTO synSiteRequest = new SitePAASDTO();
        BeanUtil.copyProperties(site, synSiteRequest);
        synSiteRequest.setShopIds(request.getShopIds());
        Wrapper wrapper = siteControllerFeign.update(synSiteRequest);
        if (wrapper.getCode() != ResponseCode.SUCCESS.getCode()) {
            System.out.println("错误信息:" + wrapper.getMessage());
            throw new BusinessException(ResponseCode.SERVICE_PLATFORM_MANAGE_ERROR);
        }

        return wrapper;
    }

    /**
     * 查询所有站点
     *
     * @author fhj
     * @date 2020/07/20
     */
    @Override
    public Wrapper<List<SiteAllResponse>> siteAll() {
        String all = "SELECT id, name FROM cf_site WHERE state = " + CommonConstant.State.STATE_START;
        List<SiteAllResponse> list = jdbcTemplate.query(all, new BeanPropertyRowMapper(SiteAllResponse.class));
        return Wrapper.success(list);
    }

    /**
     * 修改站点状态
     *
     * @param request
     * @author wrc
     * @date 2020/7/22
     */
    @Transactional
    @Override
    public Wrapper siteUpdateState(SiteUpdateStateResquest request) {
        Optional<Site> byId = siteRepository.findById(request.getId());
        if (!byId.isPresent()) {
            return Wrapper.fail("站点信息不存在");
        }
        Site site = byId.get();
        site.setId(request.getId());
        site.setUpdateTime(System.currentTimeMillis());
        site.setState(request.getState());
        siteRepository.save(site);

        SitePAASDTO synSiteRequest = new SitePAASDTO();
        synSiteRequest.setId(site.getId());
        synSiteRequest.setState(site.getState());
        Wrapper wrapper = siteControllerFeign.updateState(synSiteRequest);

        return wrapper;
    }

    /**
     * 根据模板查询所有站点
     *
     * @author fhj
     * @date 2020/08/28
     */
    @Override
    public Wrapper<List<SiteAllResponse>> allByTemplate(Long templateId) {
        List<Site> list = siteRepository.findAllByState(CommonConstant.State.STATE_START, Sort.by("id"));
        return Wrapper.success(
                list.stream().map(a -> {
                    SiteAllResponse siteAllResponse = new SiteAllResponse();
                    siteAllResponse.setId(a.getId());
                    siteAllResponse.setName(a.getName());
                    return siteAllResponse;
                }).collect(Collectors.toList())
        );
    }


}
